package com.example.nftapp.frg.find;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.example.nftapp.R;
import com.example.nftapp.act.WebActivity;
import com.example.nftapp.adapter.BannerAdapterHttp;
import com.example.nftapp.beans.BannerHttp;
import com.example.nftapp.beans.HttpResponse;
import com.example.nftapp.utils.ToastUtil;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class DiscoveryFragment extends Fragment {

    private final List<BannerHttp> bannerData = new ArrayList<>();
    private BannerAdapterHttp bannerAdapterHttp;
    //Handler+Runnable实现自动轮播
    private Handler handler;
    private ViewPager2 vpBanner;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_discovery, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TabLayout tabBanner = view.findViewById(R.id.tabBanner);
        vpBanner = view.findViewById(R.id.vpBanner);
        bannerAdapterHttp = new BannerAdapterHttp(bannerData, position -> {
            // 点击跳转至WebActivity，加载显示文章
            // ToastUtil.showToast(requireContext(), bannerData.get(position).getUrl());
            Intent intent = new Intent(requireContext(), WebActivity.class);
            intent.putExtra("url",bannerData.get(position).getUrl());
            startActivity(intent);
        });
        vpBanner.setAdapter(bannerAdapterHttp);
        new TabLayoutMediator(tabBanner, vpBanner, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                ImageView imageView = (ImageView) LayoutInflater.from(requireActivity()).inflate(R.layout.layout_custom_tab_banner, null);
                tab.setCustomView(imageView);
                if (position == 0) {
                    imageView.setImageResource(R.drawable.bg_dot_selected);
                }
            }
        }).attach();
        tabBanner.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ImageView imageView = (ImageView) tab.getCustomView();
                assert imageView != null;
                imageView.setImageResource(R.drawable.bg_dot_selected);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                ImageView imageView = (ImageView) tab.getCustomView();
                assert imageView != null;
                imageView.setImageResource(R.drawable.bg_dot_unselected);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        getBannerByHttp();
    }

    /**
     * 开启自动轮播
     */
    private void startAutoScroll() {
        handler = new Handler(Looper.getMainLooper());
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                vpBanner.setCurrentItem((vpBanner.getCurrentItem() + 1) % bannerData.size(), true);
                handler.postDelayed(this, 3000);
            }
        };
        handler.postDelayed(runnable, 3000);
    }

    /**
     * 通过Http协议，从网络获取Banner（轮播图）数据
     */
    private void getBannerByHttp() {
        new Thread(() -> {
            try {
                // 创建URL对象
                URL url = new URL("https://www.wanandroid.com/banner/json");
                // 客户端-服务器端 建立通信桥梁
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 设置请求方法为GET方法
                connection.setRequestMethod("GET");
                // 设置字符集，解决中文乱码问题
                connection.setRequestProperty("Charset", "UTF-8");
                // 进行连接
                connection.connect();
                int responseCode = connection.getResponseCode();
                if (responseCode == 200) {
                    readData(connection);
                } else {
                    // 请求失败
                    Log.e("ERROR", "请求失败，错误码：" + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 响应成功，读取数据
     *
     * @param connection
     * @throws IOException
     */
    private void readData(HttpURLConnection connection) throws IOException {
        // 请求成功，则读取服务器返回的数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
        // StringBuilder 拼接读取的结果
        StringBuilder response = new StringBuilder();
        // while循环，一次读取一行
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        renderData(response);
    }

    /**
     * 将读取到的数据，渲染/显示到UI界面
     *
     * @param response
     */
    private void renderData(StringBuilder response) {
        requireActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                HttpResponse<List<LinkedTreeMap>> httpResponse = gson.fromJson(response.toString(), HttpResponse.class);
                for (LinkedTreeMap map : httpResponse.getData()) {
                    bannerData.add(new BannerHttp((String) map.get("imagePath"), (String) map.get("url")));
                }
                bannerAdapterHttp.notifyDataSetChanged();
                startAutoScroll();
            }
        });
    }

}